package com.hzcc.hzccblog.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.hzcc.hzccblog.module.entity.po.User;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 早睡蛋
 * @Date 2022/7/15 18:51:22
 * @Desc:
 */
public class JWTUtil {
    private static String TOKEN = "hzccblog---"; //密钥

    /**
     * 使用JWT生成token
     */
    public static String createToken(User user){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_WEEK,1);
        String token = JWT.create()
                .withClaim("id",user.getId())
                .withClaim("name",user.getUserName())
                .withClaim("email",user.getUserEmail())
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(TOKEN));
        return token;
    }

    /**
     * 验证token信息
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }

    public static boolean verify2(String token) {
        Algorithm algorithm = Algorithm.HMAC256(TOKEN);
        JWTVerifier verifier = JWT.require(algorithm)
                .build();
        verifier.verify(token);
        return true;
    }

    public static String getClaim(String token, String claim) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(claim).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 验证token信息
     */
    public static Map<String,Object> verify1(String token){
        Map<String,Object> map = new HashMap<>();
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN)).build();
        DecodedJWT verify = jwtVerifier.verify(token);
        String id = verify.getClaims().get("id").asString();
        String name = verify.getClaims().get("name").asString();
        String email = verify.getClaims().get("email").asString();
        map.put("id",id);
        map.put("name",name);
        map.put("email",email);
        return map;
    }
}
